package com.tianji.tjpromotion.service.impl;

import com.tianji.tjpromotion.constants.PromotionConstants;
import com.tianji.tjpromotion.domain.po.Coupon;
import com.tianji.tjpromotion.domain.po.ExchangeCode;
import com.tianji.tjpromotion.mapper.ExchangeCodeMapper;
import com.tianji.tjpromotion.service.IExchangeCodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.tjpromotion.utils.CodeUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 兑换码 服务实现类
 * </p>
 *
 * @author yp
 * @since 2024-08-02
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class ExchangeCodeServiceImpl extends ServiceImpl<ExchangeCodeMapper, ExchangeCode> implements IExchangeCodeService {
    private final StringRedisTemplate redisTemplate;

    /**
     * 生成兑换码
     *
     * @param coupon
     */
    @Override
    @Async("generateExchangeCodeExecutor")
    public void generateCode(Coupon coupon) {
        log.info("generateCode--{}", Thread.currentThread().getId());
        //1.获得生成的数量
        Integer totalNum = coupon.getTotalNum();
        Long couponId = coupon.getId();
        //2.遍历
        Long result = redisTemplate.opsForValue().increment(PromotionConstants.COUPON_CODE_SERIAL_KEY, totalNum);
        if (result == null) {
            return;
        }
        int maxSerialNum = result.intValue();

        List<ExchangeCode> exchangeCodeLists = new ArrayList<>();
        for (int i = maxSerialNum - totalNum + 1; i <= maxSerialNum; i++) {
            //3.生成兑换码（字符串）封装成ExchangeCode 6100;
            String codeStr = CodeUtil.generateCode(i, couponId);
            ExchangeCode exchangeCode = new ExchangeCode();
            exchangeCode.setId(i);//redis自增器
            exchangeCode.setCode(codeStr);//兑换码字符串
            exchangeCode.setExchangeTargetId(couponId);//优惠卷id
            exchangeCode.setExpiredTime(coupon.getIssueEndTime());//过期时间
            exchangeCodeLists.add(exchangeCode);
        }
        //4.批量保存
        saveBatch(exchangeCodeLists);
    }
}
